<template>
  <PanerGrid @onSubmit="handleSubmit" @onReset="handleReset" :class-name="'paner-doc-list'">
    <template v-slot:search>
      <div class="d-group-items d-layout-grid d-layout-grid-4">
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">名称</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.name" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">类型(后缀)</label>
            </div>
            <div class="d-form-el">
              <div class="d-form-el">
                <input v-model="search.ext" class="d-form-input" />
              </div>
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">内容</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.data" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">路径</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.path" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">排除目录</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.ignoreDir" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">排除文件</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.ignoreFile" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">大小</label>
            </div>
            <div class="d-form-el">
              <input v-model="search.size" @keyup.enter="handleSubmit" class="d-form-input" />
            </div>
          </div>
        </div>
        <div class="d-grid-item">
          <FormCalendar
            v-model="search.createTime"
            label="创建时间"
            labelWidth="80px"
            class="d-form-group-flex"
          ></FormCalendar>
        </div>
        <div class="d-grid-item">
          <FormCalendar
            v-model="search.updateTime"
            label="修改时间"
            labelWidth="80px"
            class="d-form-group-flex"
          ></FormCalendar>
        </div>
        <div v-if="false" class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">创建人</label>
            </div>
            <div class="d-form-el">
              <input class="d-form-input" />
            </div>
          </div>
        </div>
        <div v-if="false" class="d-grid-item">
          <div class="d-form-group d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">修改人</label>
            </div>
            <div class="d-form-el">
              <input class="d-form-input" />
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:header>
      <div class="d-paner-caption">
        <span class="d-caption-text">文档列表</span>
        <div class="d-bar-tools d-bar-tools-condensed">
          <span class="d-tools-item"><a @click="handleAddDir" class="d-btn d-btn-plain-sign">添加</a></span>
          <span @click="handleDelChecked" class="d-tools-item"><button class="d-btn d-btn-plain-sign" type="button">删除</button></span>
        </div>
      </div>
      <div class="d-bar-tools d-bar-tools-right d-bar-tools-condensed">
        <a @click="handleReload" class="d-tools-item"><span class="d-btn d-btn-plain-sign d-btn-square-sm d-btn-flex"><RefreshIcon /></span></a>
      </div>
    </template>
    <template v-slot:body>
      <div class="doc-body">
        <ListMenu :data="menuList" :active="activeDir" :textKey="'name'" @onClickItem="handleClickDir" class="body-menu d-list-menu-border d-list-menu-md d-list-menu-default">
          <template v-slot:list-menu-item-tail="item">
            <span class="d-dropdown d-drop-hover d-drop-right d-inblock">
              <span class="d-drop-select"><MoreIcon /></span>
              <div class="d-list-menu d-list-cascade">
                <ul class="d-list-menu-group">
                  <li @click.stop="handleEditDir(item)" class="d-list-menu-item">
                    <a class="d-list-item-row">
                      <i class="d-list-item-icon"></i>
                      <span class="d-list-item-text">编辑</span>
                    </a>
                  </li>
                  <li v-if="isDir(item.cat)" @click.stop="handleAddDir(item)" class="d-list-menu-item">
                    <a class="d-list-item-row">
                      <i class="d-list-item-icon"></i>
                      <span class="d-list-item-text">添加</span>
                    </a>
                  </li>
                  <li @click.stop="handleDelDir(item)" class="d-list-menu-item">
                    <a class="d-list-item-row">
                      <i class="d-list-item-icon"></i>
                      <span class="d-list-item-text">删除</span>
                    </a>
                  </li>
                </ul>
              </div>
            </span>
          </template>
        </ListMenu>
        <div class="body-content">
          <Grid v-model="list" ref="gridList" :request="gridRequest" :pageSize="15">
            <!--<GridColumn :width="48" type="checkbox" />-->
            <GridColumn :width="60" type="index" label="序号" />
            <GridColumn field="name" label="名称">
              <template v-slot:body="scope">
                <a @click="downloadFile(scope)" :title="getDownloadUrl(scope)" target="_blank" class="d-text-theme d-text-linker">{{ scope.name }}</a>
              </template>
            </GridColumn>
            <GridColumn field="ext" label="类型" :width="80" />
            <GridColumn field="size" label="大小" format="capacity" :width="140" />
            <GridColumn field="path" label="路径">
              <template v-slot:body="scope">
                <span :title="scope.path">{{ scope.path }}</span>
              </template>
            </GridColumn>
            <GridColumn field="updateTime" label="修改时间" format="datetime|yyyy-MM-dd HH:mm:ss" :width="160" />
            <!-- <GridColumn field="updateUser" label="修改人" /> -->
            <GridColumn field="createTime" label="创建时间" format="datetime|yyyy-MM-dd HH:mm:ss" :width="160" />
            <!-- <GridColumn field="createUser" label="创建人" /> -->
            <GridColumn field="action" :width="160" label="操作">
              <template v-slot:body="scope">
                <div class="d-bar-tools d-bar-tools-condensed d-grid-actions">
                  <a @click="handleOpenFile(scope)" class="d-tools-item d-text-theme" title="打开所在目录"><ExploreIcon size="sm" /></a>
                  <a @click="handleReadFile(scope)" v-if="isTextFile(scope)" class="d-tools-item d-text-theme" title="查看内容"><SeeIcon size="sm" /></a>
                  <a @click="downloadFile(scope)" class="d-tools-item d-text-theme" title="下载文件"><DownloadIcon size="sm" /></a>
                  <a @click="showQRCode(scope)" class="d-tools-item d-text-theme" title="查看二维码"><QRCodeIcon size="sm" /></a>
                  <a @click="showEdit(scope)" class="d-tools-item d-text-theme" title="编辑"><EditIcon size="sm" /></a>
                  <a @click="handleDelItem(scope)" class="d-tools-item d-text-theme" title="删除"><DeleteIcon size="sm" /></a>
                </div>
              </template>
            </GridColumn>
          </Grid>
          <Content ref="contentView" />
        </div>
      </div>
      <EditDir @onSubmitSuccess="handleEditDirSuccess" ref="editDirView" />
      <Dialoger v-model="isShowQR" :dialogCls="'d-paner-xs'" :title="qrTitle" :isShowConfirm="false">
        <template v-slot:body>
          <div class="qrcode-container">
            <div id="qr_code"></div>
          </div>
        </template>
      </Dialoger>
      <Dialoger v-model="isShowEdit" :onConfirm="handleEditConfirm" :dialogCls="'d-paner-sm'" title="编辑">
        <template v-slot:body>
          <div class="d-form-group  d-form-group-flex">
            <div class="d-form-label d-text-right">
              <label class="label-text">名称</label>
            </div>
            <div class="d-form-el">
              <input v-model="editFile.name" @keyup.enter="handleEditConfirm" class="d-form-input" />
            </div>
          </div>
        </template>
      </Dialoger>
    </template>
  </PanerGrid>
</template>

<script>
import { PanerGrid } from '@daelui/vdog/dist/pages'
import { storeMemory } from '@daelui/dogjs/dist/components'
import { Grid, GridColumn, Dialoger, FormCalendar, Pager, ListMenu, ListMenuGroup, ListMenuItem } from '@daelui/vdog/dist/components'
import { zh as locale } from '@daelui/dogjs/dist/locale'
import { RefreshIcon, EditIcon, DeleteIcon, SeeIcon, MoreIcon, ExploreIcon, DownloadIcon, QRCodeIcon } from '@daelui/vdog/dist/icons'
import directSer from '../../service/action/direct.action.js'
import docSer, { api } from '../../service/action/doc.action.js'
import resolver from '../../service/components/resolver'
import stock from '../../service/stock/index.js'
import EditDir from './edit-dir.vue'
import Content from './content.vue'
import '@vendor/qrcode/1.1.0/js/qrcode.js'

export default {
  name: 'doc-list',

  components: {
    PanerGrid,
    Grid,
    GridColumn,
    RefreshIcon,
    EditIcon,
    DeleteIcon,
    SeeIcon,
    MoreIcon,
    ExploreIcon,
    DownloadIcon,
    QRCodeIcon,
    FormCalendar,
    Pager,
    ListMenu,
    ListMenuGroup,
    ListMenuItem,
    EditDir,
    Content,
    Dialoger
  },

  data () {
    return {
      // 搜索条件
      search: {
        name: '',
        ext: '',
        data: '',
        size: '',
        path: '',
        createTime: '',
        updateTime: '',
        ignoreDir: stock.state.ignoreDir
      },
      dirId: '',
      // 参数存储key
      paramsKey: 'doc',
      activeName: 1,
      // 菜单列表
      menuList: [],
      activeDir: {},
      // 表格列表
      list: [],
      // 表格请求配置
      gridRequest: {
        url: api.queryListPage.url, // 请求地址
        method: api.queryListPage.method, // 请求方式
        params: {} // 请求参数
      },
      // 文档类型
      docTypes: [],
      isShowQR: false, // 是否显示二维码
      qrTitle: '', // 二维码标题
      isShowEdit: false, // 显示编辑
      editFile: {
        name: ''
      }
    }
  },

  methods: {
    // 是否是目录
    isDir: stock.action.isDir,

    /**
     * @function 查询事件处理
    */
    handleSubmit () {
      this.$refs.gridList.reload({ pid: this.dirId, ...this.search })
      // 存储条件
      storeMemory.setItem(this.paramsKey, this.search)
    },
    /**
     * @function 刷新
    */
    handleRefresh () {
      this.$refs.gridList.refresh()
    },

    /**
     * @function 重置事件
    */
    handleReset () {
      this.search = {
        title: '',
        type: '',
        labels: '',
        data: '',
        createTime: '',
        updateTime: ''
      }
      this.gridRequest.params = this.search
    },

    /**
     * @function 点击目录事件处理
    */
    handleClickDir (item) {
      this.dirId = item.id
      this.$router.push({
        path: this.getMicroRoute('/doc/list/' + item.id)
      })
      this.handleReload()
    },

    /**
     * @function 添加目录处理
    */
    handleAddDir (item) {
      this.editInfo = {edit: false, item: item}
      this.$refs.editDirView.show(this.editInfo)
    },

    handleEditDir (item) {
      this.editInfo = {edit: true, item: item}
      this.$refs.editDirView.show(this.editInfo)
    },

    /**
     * @function 编辑成功
    */
    handleEditDirSuccess () {
      this.handleReloadDir()
    },

    /**
     * @function 删除目录
    */
    handleDelDir (item) {
      Dialoger.confirm(locale.message.confirmDelete).then(b => {
        if (!b) {
          return false
        }
        directSer.removeItem(item).then((result) => {
          if (result.success) {
            Dialoger.success(locale.action.success)
            this.handleReloadDir()
          } else {
            Dialoger.danger(locale.action.fail)
          }
        })
      })
    },

    handleReloadDir () {
      // 目录列表
      return directSer.queryTree().then(res => {
        let list = (res.data || {}).list
        list = Array.isArray(list) ? list : []
        list.forEach(item => {
          if (item.id && item.id === this.dirId) {
            this.activeDir = item
          }
        })
        this.menuList = list
        return list
      })
    },

    /**
     * @function 删除选定的数据
    */
    handleDelChecked () {
      let items = this.$refs.gridList.getChecked()
      this.removeItems(items)
    },

    /**
     * @function 删除单条数据
    */
    handleDelItem (item) {
      this.removeItems([item])
    },

    /**
     * @function 删除多条数据
    */
    removeItems (items) {
      items = Array.isArray(items) ? items : []
      if (items.length < 1) {
        Dialoger.warn(locale.list.selectOne)
        return false
      }
      Dialoger.confirm('此操作会删除系统内文件，' + locale.message.confirmDelete).then(b => {
        if (!b) {
          return false
        }
        items = items.map(item => item.id)
        docSer.removeItem(items).then(res => {
          if (!res.data) {
            Dialoger.danger('删除失败')
            return true
          }
          this.handleReload()
        })
      })
    },

    // 是否是文本文件
    isTextFile (item) {
      let exts = [
        '.json',
        '.docx',
        '.txt',
        '.xlsx',
        '.xls',
        '.sql',
        '.xml',
        '.java',
        '.yml',
        '.properties',
        '.bat',
        '.md',
        '.sh',
        '.js',
        '.css',
        '.scss',
        '.svg',
        '.html',
        '.cmd',
        '.yaml',
        '.pem',
        '.cjs',
        '.mjs',
        '.ts',
        '.vue',
        '.markdown',
        '.ejs',
        '.coffee',
        '.MIT',
        '.sass',
        '.less',
        '.php',
        '.jsx',
        '.tpl',
        '.pptx',
        '.jade',
        '.htm',
        '.as',
        '.bash',
        '.csv',
        '.LICENSE',
        '.xhtml',
        '.asp',
        '.aspx',
        '.jsp',
        '.ppt',
        '.text'
      ]
      let ext = String(item.path).toLowerCase().replace(/.+(\.\w+)$/, '$1')
      let has = exts.find(node => node.toLowerCase() === ext)
      return has
    },

    /**
     * @function 是否是文本文件
    */
    handleOpenFile (item) {
      docSer.openFileDir({path: encodeURIComponent(encodeURIComponent(item.path))})
    },

    /**
     * @function 下载文件
    */
    downloadFile (item) {
      window.open(this.getDownloadUrl(item))
    },

    /**
     * @function 获取下载地址
    */
    getDownloadUrl (item) {
      return resolver.solvePath(api.downloadFile.url) + '?path=' + encodeURIComponent(encodeURIComponent(item.path))
    },

    /**
     * @function 读取文件内容
    */
    handleReadFile (item) {
      docSer.readFile({path: item.path}).then(res => {
        this.$refs.contentView.show(res.data)
      })
    },

    /**
     * @function 重新加载
    */
    handleReload () {
      this.$refs.gridList.reload({ ...this.search, pid: this.dirId })
    },

    /**
     * @function 查看二维码
    */
    showQRCode (item) {
      this.isShowQR = true
      let url = this.getDownloadUrl(item)
      url = url.replace(/^\s*(https?:)?\/\//, location.protocol + '//')
      this.qrTitle = item.name
      this.$nextTick(() => {
        let el = document.getElementById('qr_code')
        let width = this.getWidth()
        el.innerHTML = ''
        var qrcode = new QRCode(el, {
          width: width,
          height: width,
          colorDark: this.colorDark || '#000000',
          colorLight: this.colorLight || '#ffffff',
          correctLevel: 3
        })
        qrcode.makeCode(url)
      })
    },

    // 显示编辑
    showEdit (item) {
      this.isShowEdit = true
      this.editFile = {
        path: item.path,
        name: item.name
      }
    },

    // 编辑保存
    handleEditConfirm () {
      docSer.updateName(this.editFile).then((result) => {
        if (result.success) {
          Dialoger.success(locale.action.success)
          this.handleReload()
        } else {
          Dialoger.danger(locale.action.fail)
        }
      }).catch(() => {
        Dialoger.danger(locale.action.fail)
      })
    },

    getWidth () {
      let width = parseFloat(this.width || 256)
      width = isNaN(width) ? 256 : width
      width = width < 64 ? 64 : width
      return width
    }

    /**
     * @function 编码
    */
    // encode (str) {
    //   let list = [
    //     // {code: '+', encode: '%2B'},
    //     // {code: ' ', encode: '%20'},
    //     // {code: '/', encode: '%2F'},
    //     // {code: '?', encode: '%3F'},
    //     // {code: '%', encode: '%25'},
    //     // {code: '&', encode: '%26'}
    //     // {code: '=', encode: '&3D'},
    //     // {code: '#', encode: '%23'}
    //   ]
    //   console.log(str)
    //   // list.forEach(item => {
    //   //   str = str.replace(item.code, item.encode)
    //   // })

    //   // + 空格 / ? % & = #
    //   // %2B %20 %2F %3F %25 %26 &3D %23
    //   return str
    // }
  },

  beforeMount () {
    this.dirId = this.$route?.params?.dirId || ''
    // 存储的条件
    let params = storeMemory.getItem(this.paramsKey)
    if (params) {
      this.search = Object.assign(this.search, params)
      this.gridRequest.params = this.search
    }
    this.gridRequest.params.pid = this.dirId
  },

  mounted () {
    // 加载目录列表
    this.handleReloadDir()
    // .then(list => {
    //   list = Array.isArray(list) ? list : []
    //   let item = list[0] || {}
    // })
    this.docTypes = [
      {id: '', text: '全部'},
      {id: 1, text: '目录'},
      {id: 2, text: '文件'}
    ]
  },

  activated () {
    if (this.isInitKeep) {
      this.handleRefresh()
    }
    this.isInitKeep = true
  }
}
</script>

<style lang="less" scoped>
.d-form-label {
  width: 80px;
}
.doc-body {
  flex: 1;
  display: flex;
  .body-menu {
    margin-right: 12px;
    width: 260px;
    min-height: 320px;
  }
  .body-content {
    flex: 1;
  }
}
.qrcode-container {
  text-align: center;
  /deep/img {
    margin-left: auto;
    margin-right: auto;
  }
}
</style>

<style lang="less">
.paner-doc-list {
  .d-paner-table {
    display: flex;
    flex-direction: column;
  }
  .d-paner-body {
    display: flex;
  }
}
</style>
